<template>
  <div class="login-form">
    <img class="form-img2" :src="FormImg2" alt="" />
    <div class="form">
      <div class="form-img">
        <img :src="FormImg" alt="" />
      </div>
      <p class="title">南城停车智慧停车管理平台</p>
      <div class="form-content">
        <div class="qrCodes">
          <div></div>
          <div class="qrCode-img">
            <div class="qrCode">
              扫码登录安全快捷
              <div class="el-icon-right"></div>
            </div>
            <div class="form-img3" @click="generateQRCode">
              <img :src="FormImg3" alt="" />
            </div>
          </div>
        </div>
        <div class="options">
          <div
            v-for="item in options"
            :key="item.id"
            :class="{ 'option-item': true, selected: item.selected }"
            @click="selectOption(item.id)"
          >
            {{ item.label }}
            <!-- <el-divider direction="vertical" /> -->
          </div>
        </div>
      </div>
      <el-form
        :model="form"
        class="model"
        :rules="rules"
        ref="formRef"
        v-if="optionsValue === 0"
      >
        <div v-if="nonEmpty" class="noEmpty">{{ nonError }}</div>
        <el-form-item prop="account">
          <el-input
            :prefix-icon="User"
            v-model="form.account"
            placeholder="请输入账号"
            style="width: 320px; height: 40px"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item class="pwd-input" prop="pwd">
          <el-input
            type="password"
            :prefix-icon="Lock"
            v-model="form.pwd"
            placeholder="请输入密码"
            style="width: 320px; height: 40px"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <el-form
        :model="form2"
        class="model"
        :rules="rules2"
        ref="formRef2"
        v-if="optionsValue === 1"
      >
        <div v-if="userFlag" class="noEmpty">{{ userError }}</div>
        <el-form-item prop="phone" class="phone-input">
          <el-input
            v-model="form2.phone"
            placeholder="请输入手机号"
            style="width: 320px; height: 40px"
          >
            <template #prepend>+86</template>
          </el-input>
        </el-form-item>
        <el-form-item class="pwd-input code-input" prop="code">
          <el-input
            v-model="form2.code"
            placeholder="请输入验证码"
            style="width: 320px; height: 40px"
          >
            <template #append>
              <el-button @click="getCodeData">
                <div v-if="verificationCode == '获取验证码'">
                  {{ verificationCode }}
                </div>
                <div
                  v-else-if="verificationCode == '重新获取'"
                  class="code-blue"
                >
                  {{ verificationCode }}
                </div>
                <div v-else class="code-blue">
                  {{ verificationCode }}秒后重新获取
                </div>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin2">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import FormImg from "../../../assets/image/login/logo.png";
import FormImg2 from "../../../assets/image/login/form_img.png";
import FormImg3 from "../../../assets/image/login/qr_code.png";
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref } from "vue";
import useUserStore from "../../../store/modules/user";
import {
  login,
  getQRCode,
  getUserPhone,
  getCode,
} from "../../../service/modules/user";
import { encrypt } from "../../../utils/crypto";
import { useRouter } from "vue-router";

const router = useRouter();
const nonError = ref("");
const userStore = useUserStore();
const nonEmpty = ref(false);

const options = ref([
  { id: 0, label: "密码登录", selected: true },
  { id: 1, label: "短信登录", selected: false },
]);

const optionsValue = ref(0);
const selectOption = (id) => {
  nonEmpty.value = false;
  options.value.forEach((item) => {
    if (item.id === id) {
      item.selected = true;
      optionsValue.value = id;
    } else {
      item.selected = false;
    }
  });
};

// 二维码验证
const generateQRCode = async () => {
  const res = await getQRCode({
    appid,
    redirect_uri,
  });
  console.log("res ===>", res);
};

// const form = reactive({
//   account: "gomansupm",
//   pwd: "goman123456",
// });

// 账号密码验证
const form = reactive({
  account: "",
  pwd: "",
});
const formRef = ref();

const rules = {
  account: [{ required: true, message: "请输入账号", trigger: "blur" }],
  pwd: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
};

const handleLogin = async () => {
  formRef.value.validate(async (err) => {
    if (err) {
      // userStore.userLogin(form);
      const username = {
        username: form.account,
        password: form.pwd,
        authType: "password",
      };

      const usernameStr = JSON.stringify(username);

      console.log(usernameStr);

      const res = await login({
        client_id: "CippWebApp",
        client_secret: "CippWebApp",
        grant_type: "password",
        username: usernameStr,
      });
      console.log("res ===>", res);

      if (res.data.expires_in == 7199) {
        nonEmpty.value = false;
        userStore.setInfo(res.data);
        userStore.setToken(res.data.access_token);
        router.push("/home");
      } else {
        nonEmpty.value = true;
        nonError.value = res.data.error_description;
      }
    }
  });
};

// 手机号验证
const form2 = reactive({
  phone: "",
  code: "",
});
const formRef2 = ref();

const rules2 = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "change" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确，请重新输入",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "change",
    },
  ],
};
const verificationCode = ref("获取验证码");
const userFlag = ref(false);
const userError = ref("");
const checkCodeKey = ref("");

const getCodeData = () => {
  formRef2.value.validateField("phone", (err) => {
    console.log("err ===>", err);
    if (err) {
      if (
        verificationCode.value === "获取验证码" ||
        verificationCode.value === "重新获取"
      ) {
        // 根据手机号判断用户是否存在
        getUserPhone(form2.phone).then((res) => {
          console.log("res ===>", res);
          if (res.data.result) {
            console.log("1 ===>", 1);
            userFlag.value = false;
            getCode({
              checkCodeType: "sms",
              param1: form2.phone,
            }).then((res2) => {
              console.log("res2 ===>", res2);
              checkCodeKey.value = res2.data.result.key;
            });
          } else {
            console.log("2 ===>", 2);
            userFlag.value = true;
            userError.value = form2.phone + "不存在";
          }
        });
        verificationCode.value = 120;
        let timer = setInterval(() => {
          verificationCode.value--;
          if (verificationCode.value === 0) {
            clearInterval(timer);
            verificationCode.value = "重新获取";
          }
        }, 1000);
      }
    }
  });
};

const handleLogin2 = async () => {
  formRef2.value.validate(async (err) => {
    if (err) {
      // console.log("err ===>", err);

      const username = {
        cellphone: form2.phone,
        checkcode: form2.code,
        checkcodekey: checkCodeKey.value,
        authType: "sms",
      };

      const usernameStr = JSON.stringify(username);

      console.log(usernameStr);
      const res = await login({
        client_id: "CippWebApp",
        client_secret: "CippWebApp",
        grant_type: "password",
        username: usernameStr,
      });
      console.log("res ===>", res);
      if (res.data.expires_in == 7199) {
        userFlag.value = false;
        userStore.setInfo(res.data);
        userStore.setToken(res.data.access_token);
        router.push("/home");
      } else {
        userFlag.value = true;
        userError.value = "验证码错误";
      }
    }
  });
};
</script>
<style lang="less">
.el-input .el-input__icon {
  font-size: 24px;
}
.phone-input {
  .el-input__wrapper {
    border-right: 1px solid var(--el-border-color);
    border-top: 1px solid var(--el-border-color);
    border-bottom: 1px solid var(--el-border-color);
    box-shadow: none;
  }
}
.code-input {
  .el-input__wrapper {
    border-left: 1px solid var(--el-border-color);
    border-top: 1px solid var(--el-border-color);
    border-bottom: 1px solid var(--el-border-color);
    box-shadow: none;
  }
}
</style>
<style lang="less" scoped>
.noEmpty {
  // margin: 0 auto;
  // width: 50%;
  color: #de2910;
  font-size: 12px;
}
.login-form {
  width: 860px;
  height: 470px;
  display: flex;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0px 4px 9px 0px #e1e1e1;
  .form {
    flex: 1;
    padding: 48px 90px 37px 64px;
    .form-img {
      width: 100%;
      height: 42px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 12px;
      img {
        width: 52px;
        height: 100%;
      }
    }
    .title {
      font-weight: 600;
      font-size: 26px;
      text-align: center;
      color: #333333;
      margin-bottom: 28px;
    }
    .options {
      position: absolute;
      bottom: -12px;
      display: flex;
      & > :nth-child(1) {
        margin-right: 24px;
      }
    }
    .option-item {
      cursor: pointer;
      /* 未选中状态的样式 */
      font-weight: 400;
      font-size: 16px;
      color: #666666;
      font-family: "Helvetica Neue", Helvetica, "PingFang SC",
        "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    }
    .selected {
      font-weight: bold;
      /* 选中状态的样式 */
      font-weight: 600;
      font-size: 16px;
      color: #2986ff;
      padding-bottom: 4px;
      border-bottom: 2px solid #2986ff;
      font-family: "Helvetica Neue", Helvetica, "PingFang SC",
        "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    }
    .model {
      margin-top: 32px;
      .pwd-input {
        margin-top: 20px;
        margin-bottom: 40px;
      }
      .login-btn {
        background: #409cff;
        width: 320px;
        height: 40px;
        font-weight: 500;
        font-size: 16px;
        color: #ffffff;
      }
      .code-blue {
        font-weight: 400;
        font-size: 14px;
        color: #2986ff;
      }
    }
  }
  .form-img2 {
    flex: 1;
  }
  .form-content {
    position: relative;
    top: 0;
  }
  .qrCodes {
    display: flex;
    justify-content: space-between;
    .qrCode-img {
      display: flex;
    }
    .qrCode {
      background: #a3a3a3;
      border-radius: 2px;
      width: 103px;
      height: 22px;
      line-height: 22px;
      font-weight: 400;
      font-size: 12px;
      color: #ffffff;
      text-align: center;
      margin-right: 17px;
      position: relative;
      top: 0;
    }
    .el-icon-right {
      width: 0;
      height: 0;
      border-left: 5px solid #a3a3a3;
      border-top: 5px solid transparent;
      border-bottom: 5px solid transparent;
      position: absolute;
      right: -4px;
      top: 6px;
      z-index: 999;
    }
    .form-img3 {
      // width: 100%;
      height: 54px;
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        width: 54px;
        height: 100%;
      }
    }
  }
}
</style>
